import { createContext, useContext, useState, useEffect } from 'react';
import type { ReactNode } from '../types/theme';
import type { User, LoginForm, RegisterForm } from '../types/user';

interface AuthContextType {
  user: User | null;
  isAuthenticated: boolean;
  login: (form: LoginForm) => Promise<boolean>;
  register: (form: RegisterForm) => Promise<boolean>;
  logout: () => void;
  loading: boolean;
  isLoading: boolean;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

interface AuthProviderProps {
  children: ReactNode;
}

export function AuthProvider({ children }: AuthProviderProps) {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  const isAuthenticated = !!user;

  // 从localStorage恢复用户信息
  useEffect(() => {
    const initAuth = async () => {
      try {
        const savedUser = localStorage.getItem('current-user');
        if (savedUser) {
          setUser(JSON.parse(savedUser));
        }
      } catch (error) {
        console.error('Failed to parse saved user:', error);
        localStorage.removeItem('current-user');
      } finally {
        setIsLoading(false);
      }
    };

    initAuth();
  }, []);

  const login = async (form: LoginForm): Promise<boolean> => {
    setLoading(true);
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 1000));

      // 从localStorage获取所有用户
      const users = JSON.parse(localStorage.getItem('users') || '[]') as User[];
      
      // 查找用户（支持手机号或账号登录）
      const foundUser = users.find(u => 
        (u.username === form.account || u.phone === form.account) && 
        u.password === form.password
      );

      if (foundUser) {
        setUser(foundUser);
        localStorage.setItem('current-user', JSON.stringify(foundUser));
        return true;
      } else {
        return false;
      }
    } catch {
      return false;
    } finally {
      setLoading(false);
    }
  };

  const register = async (form: RegisterForm): Promise<boolean> => {
    setLoading(true);
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 1000));

      // 从localStorage获取现有用户
      const users = JSON.parse(localStorage.getItem('users') || '[]') as User[];
      
      // 检查用户名是否已存在
      if (users.some(u => u.username === form.username)) {
        return false;
      }

      // 检查手机号是否已存在
      if (users.some(u => u.phone === form.phone)) {
        return false;
      }

      // 检查邮箱是否已存在
      if (users.some(u => u.email === form.email)) {
        return false;
      }

      // 创建新用户
      const newUser: User = {
        id: Date.now().toString(),
        username: form.username,
        password: form.password,
        name: form.name,
        gender: form.gender,
        avatar: form.avatar,
        phone: form.phone,
        email: form.email,
        createdAt: new Date().toISOString(),
        roles: ['user'],
        permissions: ['read:home', 'read:stocks', 'write:stocks'],
      };

      // 保存到localStorage
      users.push(newUser);
      localStorage.setItem('users', JSON.stringify(users));

      return true;
    } catch {
      return false;
    } finally {
      setLoading(false);
    }
  };

  const logout = () => {
    setUser(null);
    localStorage.removeItem('current-user');
    // 移除message调用，让调用方自己处理消息提示
  };

  return (
    <AuthContext.Provider value={{
      user,
      isAuthenticated,
      login,
      register,
      logout,
      loading,
      isLoading
    }}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth(): AuthContextType {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
}